package com.zhilifang.modules.zlf.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zhilifang.modules.sys.oauth2.OAuth2Filter;
import com.zhilifang.modules.zlf.entity.Banner;
import com.zhilifang.modules.zlf.entity.FooterType;
import com.zhilifang.modules.zlf.entity.Fslink;
import com.zhilifang.modules.zlf.entity.IdType;
import com.zhilifang.modules.zlf.entity.ImgUpload;
import com.zhilifang.modules.zlf.entity.Information;
import com.zhilifang.modules.zlf.entity.InformationType;
import com.zhilifang.modules.zlf.entity.Menu;
import com.zhilifang.modules.zlf.service.impl.BannerServiceImpl;
import com.zhilifang.modules.zlf.service.impl.FooterServiceImpl;
import com.zhilifang.modules.zlf.service.impl.FooterTypeServiceImpl;
import com.zhilifang.modules.zlf.service.impl.FslinkServiceImpl;
import com.zhilifang.modules.zlf.service.impl.IndexShowServiceImpl;
import com.zhilifang.modules.zlf.service.impl.IndustryServiceImpl;
import com.zhilifang.modules.zlf.service.impl.InformationServiceImpl;
import com.zhilifang.modules.zlf.service.impl.InformationTypeServiceImpl;
import com.zhilifang.modules.zlf.service.impl.MenuServiceImpl;
import com.zhilifang.modules.zlf.service.impl.SeoServiceImpl;
import com.zhilifang.modules.zlf.utils.Base64EDncrypt;
import com.zhilifang.modules.zlf.utils.Pager;
import com.zhilifang.modules.zlf.utils.Utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Controller 官网首页
 */
@Controller
public class ReceptionIndexController {

	@Autowired
	private MenuServiceImpl menuServiceImpl;
	
	@Autowired
	private BannerServiceImpl bannerServiceImpl ;
	
	@Autowired
	private InformationServiceImpl informationServiceImpl ;
	
	@Autowired
	private FslinkServiceImpl fslinkServiceImpl;
	
	@Autowired
	private FooterServiceImpl footerServiceImpl ;
	
	@Autowired
	private FooterTypeServiceImpl footerTypeServiceImpl;
	
	@Autowired
	private SeoServiceImpl seoServiceImpl ;
	
	@Autowired
    private Configuration configuration;
	
	@Autowired
	private InformationTypeServiceImpl informationTypeServiceImpl;
	
	@Autowired
	private IndexShowServiceImpl indexShowServiceImpl;
	
	@Autowired
	private IndustryServiceImpl industryServiceImpl;
	
	
	
	@GetMapping("/index")
	public String gotoReceptionIndex() {
		System.out.println("------------------官网首页------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();
		//SEO
		map.put("seo", seoServiceImpl.selectSeoId(1));
		//banner图片轮换
		List<Banner> list_1 = bannerServiceImpl.selectBannerListr();
		map.put("str", bannerTp(list_1));
		//首页内容
		map.put("list_1", indexShowServiceImpl.selectListData());
		//新闻资讯
		map.put("list_2", informationServiceImpl.selectInformationListr(999));
		//友情链接
		Fslink fslink =new Fslink();
		map.put("list_3", fslinkServiceImpl.selectFslinkListr(fslink));
		 //生成静态页面方法
		createIndexHtml("index_ftl.html", "index.ftl", map); 
		//公共底部页面加载
		publicFooter();
		return "reception/index_ftl";
	}
	
	@GetMapping("/jjfa")
	public String gotoReceptionJjfa() {
		System.out.println("------------------解决方案------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();
		//SEO
		map.put("seo", seoServiceImpl.selectSeoId(2));
		createIndexHtml("solution_ftl.html", "solution.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/solution_ftl";
	}
	
	@GetMapping("/zntc")
	public String gotoReceptionHdzl() {
		System.out.println("------------------智能体测------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();
		//SEO
		map.put("seo", seoServiceImpl.selectSeoId(3));
		createIndexHtml("solution_side_ftl.html", "solution_side.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/solution_side_ftl";
	}
	
	@GetMapping("/xlkc")
	public String gotoReceptionHdzlg() {
		System.out.println("------------------训练课程------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();    
		map.put("seo", seoServiceImpl.selectSeoId(4));
		createIndexHtml("solution_course_ftl.html", "solution_course.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/solution_course_ftl";
	}
	
	@GetMapping("/zyxt")
	public String gotoReceptionDmthy() {
		System.out.println("------------------智育系统------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();    
		map.put("seo", seoServiceImpl.selectSeoId(5));
		createIndexHtml("solution_system_ftl.html", "solution_system.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/solution_system_ftl";
	}
	
	@GetMapping("/kxtx")
	public String gotoReceptionKxtx() {
		System.out.println("------------------科学体系------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();    
		map.put("seo", seoServiceImpl.selectSeoId(6));
		createIndexHtml("scienceSystem_ftl.html", "scienceSystem.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/scienceSystem_ftl";
	}
	
	@GetMapping("/hzhb")
	public String gotoReceptionHzhb() {
		System.out.println("------------------合作伙伴------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();    
		map.put("seo", seoServiceImpl.selectSeoId(7));
		createIndexHtml("partner_ftl.html", "partner.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/partner_ftl";
	}

	@GetMapping("/xwdt")
	public String gotoReceptionXwdt() {
		System.out.println("------------------新闻动态------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();    
		map.put("seo", seoServiceImpl.selectSeoId(8));
		//分类
		List<InformationType> list_1 =  informationTypeServiceImpl.selecInformationTypeListr();
		String str ="<span data-id=\"0\" class=\"news_navTitle_active\">所有新闻</span>";
		for(int i=0;i<list_1.size();i++){
			str+="<span data-id=\""+list_1.get(i).getId()+"\">"+list_1.get(i).getName()+"</span>";
		}
		map.put("str", str);
		//列表
		List<Information> list_2 = informationServiceImpl.selectInformationListr(0);
		if(list_2.size()>0){
			for(Information list:list_2){		//内容解密
				list.setContent(Utils.analysisContent(Base64EDncrypt.decryptBASE64(list.getContent())));
			}
			//列表分页
			Pager<Information> pager=new Pager<Information>(1,6, list_2);	//默认第一页，一页显示6条
			String page  = loadPager(pager);
			map.put("list_2", pager.getDataList());
			map.put("page", page);
		}else{
			map.put("list_2", null);
			map.put("page", "");
		}
		
		createIndexHtml("news_ftl.html", "news.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/news_ftl";
	}
	
	@GetMapping("/xwxq/{id}")
	public String gotoReceptionZxxq(@PathVariable(value = "id", required = false) int id) {
		System.out.println("------------------新闻详情------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		Information  result = informationServiceImpl.selectInformationById(id);
		//内容解密
		result.setContent(Base64EDncrypt.decryptBASE64(result.getContent()));
		map.put("result", result);
		//上一页&下一页初始化
		//首先查询当前分类下的最小和最大id
		List<Information> list_2 = informationServiceImpl.selecUpInDn(result.getInformationTypeId(), id);
		IdType list_1 = informationServiceImpl.selecMinAndMaxId(result.getInformationTypeId());
		String str[] = new String[4];
		if(list_2.size()==0){
			//上一篇
			str[0]= "已经到底了";
			str[1]= "0";
			//下一篇
			str[2]= "已经到底了";
			str[3]= "0";
		}else if(list_2.size()==1){
			if(id==list_1.getMinid()){
				//上一篇
				str[0]= "已经到底了";
				str[1]= "0";
				//下一篇
				str[2]= list_2.get(0).getName();
				str[3]=list_2.get(0).getId().toString();
				//下一篇
			}else if(id==list_1.getMaxid()){
				//上一篇
				str[0]=  list_2.get(0).getName();
				str[1]= list_2.get(0).getId().toString();
				//下一篇
				str[2]= "已经到底了";
				str[3]= "0";
			}
		}else{
			//上一篇
			str[0]= list_2.get(0).getName();
			str[1]= list_2.get(0).getId().toString();
			//下一篇
			str[2]= list_2.get(1).getName();
			str[3]= list_2.get(1).getId().toString();
			//上一篇
		}
		map.put("str", str);
		createIndexHtml("news_detail_ftl"+id+".html", "news_detail.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/news_detail_ftl"+id;
	}
	
	@GetMapping("/gywm")
	public String gotoReceptionGywm() {
		System.out.println("------------------关于我们------------");
		//公共头部页面加载
		publicHeader();
		Map<String, Object> map = new HashMap<>();    
		map.put("seo", seoServiceImpl.selectSeoId(9));
		createIndexHtml("aboutUs_ftl.html", "aboutUs.ftl", map);   //生成静态页面方法
		//公共底部页面加载
		publicFooter();
		return "reception/aboutUs_ftl";
	}
	
	
	
	
	
	
	@GetMapping("/homePage")
	public String gotoBackstageHomePage() {
		System.out.println("-----------后台框架首页----------");
		return "backstage/index";
	}
	
	@GetMapping("/xpgl")
	public String gotoBackstageXpg() {
		System.out.println("-----------询盘管理----------");
		return "backstage/home";
	}
	
	@GetMapping("/syjj")
	public String gotoBackstageSyjj() {
		System.out.println("-----------首页简介----------");
		return "backstage/brief";
	}
	
	@GetMapping("/fbxw")
	public String gotoBackstageFbxw() {
		System.out.println("-----------发布新闻----------");
		return "backstage/news";
	}
	
	@GetMapping("/xxgg")
	public String gotoBackstageXxgg() {
		System.out.println("-----------形象广告----------");
		return "backstage/advert";
	}
	
	@GetMapping("/seoyh")
	public String gotoBackstageSeoyh() {
		System.out.println("-----------SEO优化----------");
		return "backstage/seo";
	}
	
	@GetMapping("/bqgl")
	public String gotoBackstageBqgl() {
		System.out.println("-----------标签管理----------");
		return "backstage/label";
	}
	
	@GetMapping("/yqlj")
	public String gotoBackstageYqlj() {
		System.out.println("-----------友情链接----------");
		return "backstage/blogroll";
	}
	
	@GetMapping("/wzdt")
	public String gotoBackstageWzdt() {
		System.out.println("-----------网站地图----------");
		return "backstage/sitemap";
	}
	
	@GetMapping("/wztj")
	public String gotoBackstageWztj() {
		System.out.println("-----------网站统计----------");
		return "backstage/statistics";
	}
	
	/**
	 * 后台退出。注销session
	 * @return
	 */
	@GetMapping("/logout")
	public String gotoBackstageWztj(HttpSession session) {
		System.out.println("-----------退出----------");
		if(session.getAttribute(OAuth2Filter.SESSION_KEY)!=null){
				session.removeAttribute(OAuth2Filter.SESSION_KEY);
		}
		return "login";
	}
	
	
	/**
	 * 底部公共菜单加载
	 */
	public void publicFooter(){
		System.out.println("------------------公共底部菜单------------");
		Map<String, Object> map = new HashMap<>();    
		List<FooterType> list_1 = footerTypeServiceImpl.selectFooterTypeListr();
		map.put("list_1", list_1);
		for(int i=0;i<list_1.size();i++){
			map.put("footer_"+i, footerServiceImpl.selecFooterListr(list_1.get(i).getId()));
		}
		createIndexHtml("footer.html", "footer.ftl", map);   //生成静态页面方法
	}
	
	
	/**
	 * 头部公共菜单加载
	 */
	public void publicHeader(){
		System.out.println("------------------公共头部菜单------------");
		Map<String, Object> map = new HashMap<>();    
		List<Menu> list_1 = menuServiceImpl.selectMenuListr();
		map.put("list_1", list_1);
		map.put("header_2", industryServiceImpl.selectByPMenuId(list_1.get(1).getId()));
		createIndexHtml("header.html", "header.ftl", map);   //生成静态页面方法
	}
	
	
	
	   /**
     * 首页banner图片html拼接
     * @return
     */
    public String[] bannerTp(List<Banner> list){
    	 String str1 = "";     //图片
    	 String 	str2 = "";     //指示符
    	 for(int i=0;i<list.size();i++){
		    if(i==0){
		    	str1+="<div class=\"carousel-item active\">";
		    	str2+="<li data-target=\"#banner\" data-slide-to=\""+i+"\" class=\"active\"></li>";
		    }else{
		    	str1+="<div class=\"carousel-item\">";
		    	str2+="<li data-target=\"#banner\" data-slide-to=\""+i+"\"></li>";
		    }
		    str1+="<a href=\""+list.get(i).getUrl()+"\">";
		    str1+="<img src=\""+list.get(i).getImgurl()+"\" title=\""+list.get(i).getTitle()+"\" alt=\""+list.get(i).getAlt()+"\">";
		    str1+="</a>";
		    str1+="</div>";
    	 }
    	String[] strArray = {str1,str2};
    	return strArray;
    }
	
	
	
	
	/**
     * 生成首页静态页面
     * 生成文件名称、调用模板名称、存放数据
     * 
     */
    public void createIndexHtml(String fileName, String ftlName, Map<String, Object> map) {
        try {
            /**获取输出目标文件输出流------开始*/
            String filepath = this.getClass().getResource("/").toURI().getPath()+"views/reception/";
            System.out.println("每次访问新生成的html位置："+filepath);
            File folder = new File(filepath);
            //如果文件夹不存在
            if (!folder.exists()) {
                folder.mkdir();
            }
            File indexHtml = new File(folder, fileName);
            //如果html文件不存在
            if (!indexHtml.exists()) {
                indexHtml.createNewFile();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(indexHtml),"UTF-8"));
            /**获取输出目标文件输出流------结束*/
            //获取模板
            Template template = configuration.getTemplate(ftlName);
            //把数据和输出文件信息交给模板得到静态html文件
            template.process(map,out);
            out.flush();
            out.close();}
        catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
    
    
    /**
	 * 公共接收图片上传
	 * type  文件夹类型
	 * 
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/imgUpload", method = RequestMethod.POST)
	@ResponseBody
	public ImgUpload imgUpload(@RequestParam("img") MultipartFile list , String type) throws IllegalStateException, IOException{
		ImgUpload result = new ImgUpload();
		String[] data = new String[5];
		if(type==""||type==null){
			type ="index";
		}
		String path = Utils.isLinux(type);  		//判断当前系统类型，根据系统类型存放文件
		//创建图片文件夹存放图片
        File fileDir = new File(path);
        //判断文件夹是否存在
        if(!fileDir.exists()){
            //不存在的话,创建文件夹
            fileDir.mkdirs();
        }
        String fileName = returnPrefixSuffixName(list.getOriginalFilename());
        fileDir = new File(path+fileName);
        list.transferTo(fileDir);//实现文件的上传
		data[0]="/localImg/"+type+"/"+fileName;
        result.setErrno("0");
        result.setData(data);
		return result;
	}
	
	/**
	 * 随机生成文件名称
	 * 名称当前时间+随机数+文件后缀名
	 * 
	 */
	public String returnPrefixSuffixName(String fileName) {
		long time = new Date().getTime() + Math.round(Math.random() * 1000);  //生成随机数
        String prefix = time + "";  //类型转换
		String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
		String suffix =  "."+strArray[suffixIndex];  //生成文件后缀名
		return prefix+suffix;
	}
	
	/**
	 * 新闻资讯分页拼接
	 * 
	 */
	public String loadPager(Pager<Information> pager){
		String str = "";
		str += "<li><a class=\"first\"></a></li>";
		str += "<li><a class=\"prev\" id=\"prePage\">&lt;</a></li>";
		int startindex = pager.getCurrentPage();  //当前页数
		int endindex = pager.getTotalPage();  //总页数
		int spacenumb = endindex - startindex;
		if (spacenumb > 5) {
			endindex = startindex + 4;
		} else {
			if (pager.getTotalPage() > 5) {
				startindex = pager.getTotalPage() - 4;
			} else {
				startindex = 1;
			}
		}
		for (int i = startindex; i <= endindex; i++) {
			if (pager.getCurrentPage() == i) {  //active默认选中样式
				str += "<li class=\"active\" data-num=\""+i+"\"><a>" + i + "</a></li>";
			} else {
				str += "<li data-num=\""+i+"\"><a>" + i + "</a></li>";
			}
		}
		str += "<li><a class=\"next\"  id=\"nextPage\">&gt;</a></li>";
		str += "<li><a class=\"last\"></a></li>";
		return str;
	}
	
	
	
}
